﻿using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Threading;

namespace Elderos.TextSearchers
{
	public class DbTextManager : ITextManager
	{

	    public int BufferSize
	    {
	        get { return _bufferSize; }
	        set { _bufferSize = value; }
	    }

	    private int _lastID;

		private string[] _buffer;
		private int _currentIndex = -1;
	    private int _bufferSize = 100000;

	    private object _locker = new object();

	    public DbTextManager()
	    {
	        _buffer = new string[BufferSize];
	    }

		public string GetNextText()
		{
		    lock (_locker)
		    {
                if (_currentIndex < 0 || _currentIndex > BufferSize - 1)
                    ReloadBuffer();
                string result = _buffer[_currentIndex];
		        _currentIndex++;
                return result;
            }
		}

		private void ReloadBuffer() 
		{
			string cstring = ConfigurationManager.ConnectionStrings["Articles"].ConnectionString;
			using (var connection = new SqlConnection(cstring))
			using (var cmd = connection.CreateCommand())
			{
				cmd.CommandText =
					@"select top "+BufferSize+@" a.ID, a.Title, a.Body
from Articles a
where a.ID > @current
order by a.ID asc";
				cmd.Parameters.AddWithValue("@current", _lastID);

				connection.Open();
				using (var reader = cmd.ExecuteReader())
				{
					for (int i = 0; i < BufferSize; i++)
					{
						if (!reader.Read())
							_buffer[i] = null;
						else
						{
							if (reader.GetInt32(0) > _lastID)
								_lastID = reader.GetInt32(0);
							string title = reader.GetString(1);
							string body = reader.GetString(2);
							string text = title + "\r\n" + body;
							_buffer[i] = text;
						}
					}
					_currentIndex = 0;
				}
			}
		}
	}
}
